import { useState, useEffect, useContext, useRef } from 'react'
import PanelLeft from '../../../../../common/PanelLeft';
import DarkBtn from '../../../../../common/DarkBtn';
import DarkCard from '../../../../../common/DarkCard';
import { Button, Collapse, Tooltip, Tree } from 'antd';
import GlobalContext from '../../../../../../utils/GlobalContext';
import useBusinessMap from '../../../../../common/BusinessMap/useBusinessMap';
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import Api from '../../../../../../utils/api';
import FetchHelper from '../../../../../../utils/helper/fetch-helper';
import { dataToFeature, navByWkt, createLayer } from '../../../../../../utils/helper/mapHelper';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import Circle from 'ol/style/Circle';
import CztApi from '../../../../../../utils/apis/CztApi';
import { LeftOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import useMapGlobal from '../../../../../common/BusinessMap/useMapGlobal';
import JzzyApi from '../../../../../../utils/apis/JzzyApi';
import ZhfxApi from '../../../../../../utils/apis/ZhfxApi';
import ZdfhApi from '../../../../../../utils/apis/ZdfhApi';
import { Icon } from 'ol/style';
import { resourcePath } from '../../../../../../utils/resource';
import { Overlay } from 'ol';
import bootstrap from 'bootstrap/dist/js/bootstrap.bundle';
import { feature } from 'caniuse-lite';
import { cacheDatas } from '../../../../../../utils/constant';

const generateData = (datas, dl) => {
    datas.forEach(data => {
        data.dl = dl;
        if (data.children) {
            generateData(data.children, dl)
        }
    });
    return datas
}

function Popup({ title, position }) {



    return (

        <div style={{
            position: 'absolute',
            left: `${position.x}px`,
            top: `${position.y - 50}px`,
            display: 'inline-block',
            whiteSpace: 'nowrap',
            borderRadius: 10,/* 设置圆角半径 */
            backgroundColor: 'black', /* 设置背景色为黑色 */
            padding: 10, /* 可选：添加内边距以增加可读性 */
            color: 'white',
        }}>{title} </div>

    );
}

export default function LayerManager(props) {

    const map = useBusinessMap();
    const [layers, setLayers] = useState([])
    const [visible, setVisible] = useState(true);

    const [layerDatas, setLayerDatas] = useState([]);

    const [mapGlobal, setMapGlobal] = useMapGlobal();

    const [position, setPosition] = useState({ x: 0, y: 0 });

    useEffect(() => {
        const handleMouseMove = (event) => {
            setPosition({ x: event.pageX, y: event.pageY });

        };

        window.addEventListener('mousemove', handleMouseMove);

        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
        };
    }, []);

    useEffect(() => {
        //const resp_1 = FetchHelper.getJson(`/admin-api/ybyj/yhsj/count/by/yhlb`)
        //const resp_2 = FetchHelper.getJson(`/admin-api/ybyj/yhsj/list`)
        //const resp_3 = FetchHelper.getJson(`/admin-api/ybyj/yhsj/list`)
        //const resp_4 = FetchHelper.getJson(`/admin-api/ybyj/yhsj/list`)
        Promise.all([Api.getZhfxCategroy(), Api.getCztCategroy(), Api.getJzzyCategroy(), Api.getZdfhCategroy(), FetchHelper.getJson(`/admin-api/ybyj/yhsj/count/by/yhlb`), FetchHelper.getJson(`/admin-api/ybyj/czt/countZl`), FetchHelper.getJson(`/admin-api/ybyj/jzzy/countZl`)]).then(([resp1, resp2, resp3, resp4, resp_1, resp_2, resp_3]) => {
            resp1.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                const datas = resp_1.data.filter(d => {
                    return d.yhlb && e.title.includes(`${d.yhlb}`)
                })
                e.count = `${e.title} (${_.sumBy(datas, 'count')}) `; // 更新 count
                // 遍历 resp_1.data
                // resp_1.data.forEach((c,i) => {
                //     // 检查 title 是否包含 yhlb
                //     if (e.title.includes(`${c.yhlb}`)) {
                //         console.log("@:true1", e, c); // 输出匹配信息
                //         e.count = `${e.title} (${c.count}) `; // 更新 count
                //     }
                // });

                //console.log("@:", e, resp_1); // 输出当前元素及 resp_1
            });
            resp2.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                // 遍历 resp_1.data
                resp_2.data.forEach((c, i) => {
                    // 检查 title 是否包含 yhlb
                    if (e.title.includes(`${c.cztzl === "" ? null : c.cztzl}`)) {
                        console.log("@:true2", e, c); // 输出匹配信息
                        e.count = `${e.title} (${c.count ? c.count : 0}) `; // 更新 count
                    }
                });

                console.log("@:", e, resp_2); // 输出当前元素及 resp_1
            });
            resp3.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                // 遍历 resp_1.data
                resp_3.data.forEach((c, i) => {
                    // 检查 title 是否包含 yhlb
                    //console.log("@:true<-", e.title, c.jzzyzl);
                    if (e.title.includes(`${c.jzzyzl}`)) {
                        //console.log("@:true", e.title, c.jzzyzl); // 输出匹配信息
                        e.count = `${e.title} (${c.count ? c.count : 0}) `; // 更新 count
                    }
                });

                //console.log("@:", e, resp_3); // 输出当前元素及 resp_1
            });
            resp4.map((e, i) => {
                if (e.children) {
                    e.children.map(r => {
                        r.count = r.title
                        return r
                    })
                }
                //console.log("@:",e,resp_1)
                e.count = `${e.title} ( 0 ) `;
                return e
            });
            setLayerDatas([{
                title: "灾害风险",
                children: generateData(resp1, 'zhfx'),
                dl: 'zhfx'
            }, {
                title: "承灾体",
                children: generateData(resp2, 'czt'),
                dl: 'czt'
            }, {
                title: "减灾资源",
                children: generateData(resp3, 'jzzy'),
                dl: 'jzzy'
            },

            {
                title: "重点防护目标",
                children: generateData(resp4, 'zdfh'),
                dl: 'zdfh'
            }

            ])
        })
    }, [])


    useEffect(() => {
        if (!map) {
            return;
        }
        const layers = [];
        const generate = (datas) => {
            datas.forEach(data => {
                if (data.children) {
                    generate(data.children);
                } else {
                    layers.push(data);
                }
            })
        }
        generate(layerDatas)

        setLayers(layers.map(layerInfo => {
            let style;
            if (layerInfo.style) {
                let styleJson = {};
                if (layerInfo.style.fill) {
                    styleJson.fill = new Fill({
                        ...layerInfo.style.fill
                    });
                }
                if (layerInfo.style.stroke) {
                    styleJson.stroke = new Stroke({
                        ...layerInfo.style.stroke
                    });
                }

                if (layerInfo.style.circle) {
                    const circle = { ...layerInfo.style.circle }
                    if (circle.fill) {
                        circle.fill = new Fill({
                            ...circle.fill
                        })
                    }
                    if (circle.stroke) {
                        circle.stroke = new Stroke({
                            ...circle.stroke
                        })
                    }
                    styleJson.image = new Circle({
                        ...circle
                    });
                }
                style = new Style(styleJson)
            }

            const l = new VectorLayer({
                name: layerInfo.title,
                visible: false,
                style,
                source: new VectorSource({
                    loader: function (extent, resolution, projection, success, failure) {
                        if (layerInfo.dl === 'zhfx') {
                            ZhfxApi.list({
                                yhlx: layerInfo.title,
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                /* 部分数据只有经纬度，无坐标信息，在此处理一下 */
                                const abcd = resp.rows.map(e => {
                                    if (e?.geom) {
                                        return e
                                    } else if (!e?.geom && e.jd && e.wd) {
                                        return { ...e, geom: `POINT(${e.jd} ${e.wd})` }
                                    }
                                    return e;
                                })
                                //console.log('1', abcd)
                                /*  */
                                const features = abcd.filter(data => data.geom).map(data => {
                                    const feature = dataToFeature(data);
                                    const yhlx = layerInfo.title;
                                    // console.log('layerInfo.title',yhlx)
                                    // console.log('layerInfo',layerInfo)
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[yhlx],
                                            scale: 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    //console.log('layerInfo', feature, iconStyle)
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        }
                        else if (layerInfo.dl === 'czt') {
                            ZdfhApi.list({
                                cztxl: layerInfo.title
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                const features = resp.rows.filter(data => {
                                    if (data.geom) {
                                        return data.geom
                                    } else if (data.xq) {
                                        const a = JSON.parse(data.xq)
                                        if (a.longitude && a.latitude) {
                                            data.geom = `POINT(${a.longitude} ${a.latitude})`
                                            return data.geom
                                        }
                                    }

                                }).map(data => {
                                    const feature = dataToFeature(data);
                                    const cztxl = layerInfo.title;
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[cztxl],
                                            scale: 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        } else if (layerInfo.dl === 'jzzy') {
                            JzzyApi.list({
                                jzzyxl: layerInfo.title
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                const features = resp.rows.filter(data => data.geom).map(data => {
                                    const feature = dataToFeature(data);
                                    const jzzyxl = layerInfo.title;
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[jzzyxl],
                                            scale: 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        }
                        else if (layerInfo.dl === 'zdfh') {
                            if (layerInfo.title === "监测监控台站") {
                                ZdfhApi.monitor({
                                    jcdlx: layerInfo.title
                                }).then(resp => {
                                    cacheDatas[layerInfo.title] = resp.rows;
                                    const features = resp.rows.filter(data => data.geom
                                    ).map(data => {
                                        const feature = dataToFeature(data);
                                        const jcdlx = layerInfo.title;
                                        const iconStyle = new Style({
                                            image: new Icon({
                                                src: resourcePath.iconMap[jcdlx],
                                                scale: 0.6,
                                                anchor: [0.5, 1]
                                            })
                                        })
                                        feature.setStyle(iconStyle)
                                        feature.set('layerName', layerInfo.title)
                                        return feature;
                                    })
                                    this.addFeatures(features)
                                })
                            }
                            else {
                                ZdfhApi.list({
                                    cztxl: layerInfo.title
                                }).then(resp => {
                                    cacheDatas[layerInfo.title] = resp.rows;
                                    const features = resp.rows.filter(data => {
                                        if (data?.fhjb > 2) {
                                            return data.geom
                                        } else {
                                            return null;
                                        }
                                    }
                                    ).map(data => {
                                        const feature = dataToFeature(data);
                                        const cztxl = layerInfo.title;
                                        const iconStyle = new Style({
                                            image: new Icon({
                                                src: resourcePath.iconMap[cztxl],
                                                scale: 0.6,
                                                anchor: [0.5, 1]
                                            })
                                        })
                                        feature.setStyle(iconStyle)
                                        feature.set('layerName', layerInfo.title)
                                        return feature;
                                    })
                                    this.addFeatures(features)
                                })
                            }

                        }
                    }
                })
            });
            l.set('__tpye', 'businessLayer')
            l.set('dl', layerInfo.dl)
            map.addLayer(l)
            return l;
        }))

    }, [map, layerDatas])

    const [title, setTiltle] = useState();
    const popupRef = useRef();
    // const div = document.createElement("div");
    // popupRef.current?.appendChild(div);
    useEffect(() => {
        if (map) {
            const handler = evt => {
                const popup = new Overlay({
                    element: popupRef.current,
                });
                map.addOverlay(popup);
                const features = map.getFeaturesAtPixel(evt.pixel);
                // console.log('features',features)
                const item = features?.find(feature => feature.get('yhlx'))?.getProperties();
                const item1 = features?.find(feature => feature.get('jcdlx'))?.getProperties();
                const item2 = features?.find(feature => feature.get('jzzyxl'))?.getProperties();
                const item3 = features?.find(feature => feature.get('cztxl'))?.getProperties();
                const coordinate = features?.find(feature => feature.get('yhlx'))?.getGeometry()?.getCoordinates();
                const coordinate1 = features?.find(feature => feature.get('jcdlx'))?.getGeometry()?.getCoordinates();
                const coordinate2 = features?.find(feature => feature.get('jzzyxl'))?.getGeometry()?.getCoordinates();
                const coordinate3 = features?.find(feature => feature.get('cztxl'))?.getGeometry()?.getCoordinates();
                if (coordinate) {
                    popup.setPosition(coordinate);
                } else if (coordinate1) {
                    popup.setPosition(coordinate1);
                } else if (coordinate2) {
                    popup.setPosition(coordinate2);
                } else {
                    popup.setPosition(coordinate3);
                }
                const tooltip = item?.yhmc;
                const tooltip1 = item1?.zdm;
                const tooltip2 = item2?.jzzymc;
                const tooltip3 = item3?.cztmc;
                if (tooltip) {
                    setTiltle(tooltip);
                } else if (tooltip1) {
                    setTiltle(tooltip1);
                } else if (tooltip2) {
                    setTiltle(tooltip2);
                } else {
                    setTiltle(tooltip3);
                }

                // let popover = bootstrap.Popover.getInstance(popupRef.current);
                // if (popover) {
                //     popover.dispose();
                // }
                // popover = new bootstrap.Popover(popupRef.current, {
                //     animation: false,
                //     container: popupRef.current,
                //     content: null,
                //     html: true,
                //     placement: 'right',
                //     trigger:['hover']
                    
                // });
                // popover.show();
            }
            map.on('pointermove', handler);
            return () => {
                map.un('pointermove', handler);
            }
        }
    }, [map])


    return <>
        <div className='layout-v' style={{
            position: "absolute",
            left: 20,
            top: 20,
            bottom: 20,
            overflow: 'auto'
        }}>
            {!visible && <DarkBtn placement="right" title="资源目录" icon={<MenuUnfoldOutlined />} onClick={e => {
                setVisible(true)

            }}></DarkBtn>}
            {visible && <>
                <DarkCard className="layout-h center" style={{
                    width: 300,
                    // height: 42,
                    marginBottom: 10,
                    fontSize: 20,
                    fontWeight: 'bold',
                }}>
                    <div className='fill'>资源目录</div>
                    <Button title="收起" icon={<MenuFoldOutlined />} type={'text'} onClick={e => {
                        setVisible(false)
                        //setTiltle(false)
                    }}></Button>
                </DarkCard>
                <DarkCard className="fill h0" style={{
                    width: 300,
                    overflow: "auto"
                    // height: 300
                }}>
                    {layerDatas.map(layerData => {
                        return <Collapse key={layerData.title} defaultActiveKey={['灾害风险', '承灾体', '减灾资源', '重点防护目标']} style={{
                            marginBottom: 12
                        }}>
                            <Collapse.Panel key={layerData.title} header={layerData.title}>
                                <Tree treeData={layerData.children} fieldNames={{
                                    title: 'count',
                                    key: 'title',
                                    children: 'children',
                                }} checkable
                                    onCheck={(checkedKeys, { checked, checkedNodes }) => {
                                        console.log("11112", layerData)
                                        layers.filter(layer => {
                                            return layer.get('dl') === layerData.dl;
                                        }).forEach(layer => {
                                            if (checkedKeys.find(key => key === layer.get('name'))) {
                                                layer.set('visible', true)
                                            } else {
                                                layer.set('visible', false)
                                            }
                                        }
                                        );
                                        setMapGlobal(global => {
                                            return {
                                                ...global,
                                                visibleLayers: layers.filter(layer => {
                                                    return layer.get('visible');
                                                })
                                            }
                                        })
                                    }}
                                />
                            </Collapse.Panel>
                        </Collapse>
                    })}
                </DarkCard>


            </>}


        </div>
        {title && <Popup title={title} ref={popupRef} position={position} />}
    </>

}